package com.smz.controller;

import com.smz.entity.Menu;
import com.smz.service.MenuService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class MenuController {
    @Autowired
    MenuService menuService;


    @GetMapping("/menus/username")
    public ResponseEntity<List<Menu>> findAllMenu(){
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal!=null){
            List<Menu> menu = menuService.findAllMenuByUsername(principal.getUsername());
            return ResponseEntity.ok(menu);
        }
        return null;
    }


    @GetMapping("/menu")
    public ResponseEntity<List<Menu>> listWithTree(){
        List<Menu> menus = menuService.listWithTree();
        return ResponseEntity.ok(menus);
    }

    @ApiOperation("增加分类")
    @PostMapping("/menu")
    public ResponseEntity<String> addMenu(@RequestBody Menu menu){
        menuService.addMenu(menu);
        return ResponseEntity.ok("ok");
    }



    @ApiOperation("更新分类")
    @PutMapping("/menu")
    public ResponseEntity<String> modifyMenu(@RequestBody Menu menu){
        menuService.modifyMenu(menu);
        return ResponseEntity.ok("ok");
    }

    @ApiOperation("删除分类")
    @DeleteMapping("/menu/{pid}")
    public ResponseEntity<String> removeMenuByIdAndPid(@PathVariable("pid") Integer id){
        menuService.deleteMenuByIdAndPid(id);
        return ResponseEntity.ok("ok");
    }


}
